package org.usmile.algorithms.leetcode.middle;

import java.util.ArrayList;
import java.util.List;

/**
 * 54. 螺旋矩阵
 *
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 *
 * 示例 1：
 *
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 * 示例 2：
 *
 * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 *
 * 提示：
 *
 * m == matrix.length
 * n == matrix[i].length
 * 1 <= m, n <= 10
 * -100 <= matrix[i][j] <= 100
 */
public class _0054 {
}

class _0054_Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int rows = matrix.length;
        int cols = matrix[0].length;

        int row = 0, col = 0;
        int direction = 0;
        List<Integer> result = new ArrayList<>();
        boolean[][] seen = new boolean[rows][cols];
        for (int i = 0; i < rows * cols; i++) {
            result.add(matrix[row][col]);
            seen[row][col] = true;

            int nextRow = row + directions[direction][0];
            int nextCol = col + directions[direction][1];

            if (nextRow < 0 || nextRow >= rows
                    || nextCol < 0 || nextCol >= cols
                    || seen[nextRow][nextCol]) {
                // 改变方向
                direction = (direction + 1) % 4;
            }

            row = row + directions[direction][0];
            col = col + directions[direction][1];
        }

        return result;
    }
}
